package com.choco.batch;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;

/**
 * @author choco
 * @date 2021/12/4 14:15
 */
@Slf4j
public class WordCount {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //读取文件
        DataSource<String> dataSource = env.readTextFile("src/main/resources/hello.txt");

        //处理数据
        AggregateOperator<Tuple2<String, Integer>> dataSet = dataSource.flatMap((FlatMapFunction<String, Tuple2<String, Integer>>) (s, collector) -> {
            String[] strings = s.split(" ");
            for (String string : strings) {
                collector.collect(new Tuple2<>(string, 1));
            }
        }).groupBy(0).sum(1);

        dataSet.print();
    }
}
